include(${CMAKE_CURRENT_LIST_DIR}/json.cmake)
# Test CALLBACK script. Prints output information and verifies index file
# Called as: cmake -P hook.cmake [CheckForStaticQuery?] [index.json]
set(index ${CMAKE_ARGV4})
if (NOT ${CMAKE_ARGV3})
  set(hasStaticInfo "UNEXPECTED")
endif()
read_json(${index} contents)
string(JSON hook GET "${contents}" hook)

# Output is verified by *-stdout.txt files that the HOOK is run
message(STATUS ${hook})
# Not a check-*.cmake script, this is called as an instrumentation CALLBACK
set(ERROR_MESSAGE "")
macro(add_error error)
  string(APPEND ERROR_MESSAGE "${error}\n")
endmacro()

macro(has_key key json)
  cmake_parse_arguments(ARG "UNEXPECTED" "" "" ${ARGN})
  unset(missingKey)
  string(JSON ${key} ERROR_VARIABLE missingKey GET "${json}" ${key})
  if (NOT ARG_UNEXPECTED AND NOT "${missingKey}" MATCHES NOTFOUND)
    add_error("\nKey \"${key}\" not in index:\n${json}")
  elseif(ARG_UNEXPECTED AND "${missingKey}" MATCHES NOTFOUND)
    add_error("\nUnexpected key \"${key}\" in index:\n${json}")
  endif()
endmacro()

has_key(version ${contents})
has_key(buildDir ${contents})
has_key(dataDir ${contents})
has_key(snippets ${contents})

if (NOT ${version} EQUAL 1)
    add_error("Version must be 1, got: ${version}")
endif()

string(JSON length LENGTH ${snippets})
math(EXPR length ${length}-1)
foreach(i RANGE ${length})
  string(JSON filename GET "${snippets}" ${i})
  if (NOT EXISTS ${dataDir}/${filename})
    add_error("Listed snippet: ${dataDir}/${filename} does not exist")
  endif()
endforeach()

has_key(staticSystemInformation ${contents} ${hasStaticInfo})
has_key(OSName ${staticSystemInformation} ${hasStaticInfo})
has_key(OSPlatform ${staticSystemInformation} ${hasStaticInfo})
has_key(OSRelease ${staticSystemInformation} ${hasStaticInfo})
has_key(OSVersion ${staticSystemInformation} ${hasStaticInfo})
has_key(familyId ${staticSystemInformation} ${hasStaticInfo})
has_key(hostname ${staticSystemInformation} ${hasStaticInfo})
has_key(is64Bits ${staticSystemInformation} ${hasStaticInfo})
has_key(modelId ${staticSystemInformation} ${hasStaticInfo})
has_key(numberOfLogicalCPU ${staticSystemInformation} ${hasStaticInfo})
has_key(numberOfPhysicalCPU ${staticSystemInformation} ${hasStaticInfo})
has_key(processorAPICID ${staticSystemInformation} ${hasStaticInfo})
has_key(processorCacheSize ${staticSystemInformation} ${hasStaticInfo})
has_key(processorClockFrequency ${staticSystemInformation} ${hasStaticInfo})
has_key(processorName ${staticSystemInformation} ${hasStaticInfo})
has_key(totalPhysicalMemory ${staticSystemInformation} ${hasStaticInfo})
has_key(totalVirtualMemory ${staticSystemInformation} ${hasStaticInfo})
has_key(vendorID ${staticSystemInformation} ${hasStaticInfo})
has_key(vendorString ${staticSystemInformation} ${hasStaticInfo})

if (NOT ERROR_MESSAGE MATCHES "^$")
  message(FATAL_ERROR ${ERROR_MESSAGE})
endif()
